package com.jiayou.session

import com.jiayou.AuthenticatePackage
import com.jiayou.DefaultProtocolImpl
import com.jiayou.emnu.FrameType
import com.jiayou.tool.objectToByteArray
import io.ktor.network.sockets.*
import io.ktor.utils.io.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
@author lishuang
@data   2021-04-23  08:59:33
@info   默认客户端session实现
 */
class DefaultClientSocketSession(
    override var authenticatePackage: AuthenticatePackage<String, String, String>? = null
) : ClientSocketSession<String, String, String> {
    companion object {
        val logger: Logger = LoggerFactory.getLogger(DefaultServerSocketSession::class.java)
    }

    override fun onError(socket: Socket) = if (!socket.isClosed) socket.close() else Unit

    override suspend fun onWaitClosed(socket: Socket) = socket.awaitClosed()

    //在打开连接时第一时间发送自己的身份信息
    override suspend fun onOpen(socket: Socket, output: ByteWriteChannel, input: ByteReadChannel) {
        val objectToByteArray = objectToByteArray(DefaultProtocolImpl(FrameType.Auth, authenticatePackage))
        output.writeInt(objectToByteArray.size)
        output.writeFully(objectToByteArray)
    }

}